package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import dto.PageResultDTO;
import dto.ResultDTO;
import dto.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {
    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 增加
     */
    @PostMapping
    public ResultDTO add(@RequestBody Spit spit) {
        this.spitService.saveSpit(spit);
        return new ResultDTO(true, StatusCode.OK, "增加成功");
    }

    /**
     * 删
     */
    @DeleteMapping("/{id}")
    public ResultDTO del(@PathVariable String id) {
        this.spitService.deleteSpit(id);
        return new ResultDTO(true, StatusCode.OK, "删除成功");
    }

    /**
     * 改
     */
    @PutMapping("/{id}")
    public ResultDTO update(@RequestBody Spit spit, @PathVariable String id) {
        spit.setId(id);
        this.spitService.updateSpit(spit);
        return new ResultDTO(true, StatusCode.OK, "修改成功");
    }

    /**
     * 查询全部数据
     */
    @GetMapping
    public ResultDTO list() {
        return new ResultDTO(true, StatusCode.OK, "查询成功", this.spitService.findAll());
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public ResultDTO queryById(@PathVariable String id) {
        return new ResultDTO(true, StatusCode.OK, "查询成功", this.spitService.findSpitById(id));
    }

    /**
     * 根据上级ID查询吐槽列表（分页）
     */
    @GetMapping("/comment/{parentid}/{pageNum}/{size}")
    public ResultDTO listPageByParentId(@PathVariable String parentid, @PathVariable int pageNum, @PathVariable int size) {
        Page<Spit> page = this.spitService.findByParentid(parentid, pageNum, size);
        return new ResultDTO(true, StatusCode.OK, "查询成功", new PageResultDTO<Spit>(page.getTotalElements(), page.getContent()));
    }

    /**
     * 点赞
     */
    @PutMapping("/thumbup/{id}")
    public ResultDTO incrementThumbup(@PathVariable String id) {
        //目标：某用户24小时内只能点赞一次
        //1)获取当前登录的用户，后边我们会修改为真正的当前登陆的用户（先写死）
        String userid = "2023";

        //2)定义已经点赞的用户在Redis中存放的key
        String redisKey = "thumbup_" + userid + "_" + id;

        // 判断用户是否点过赞
        if (null != this.redisTemplate.opsForValue().get(redisKey)) {
            // 存在
            return new ResultDTO(false, StatusCode.REPERROR, "您已经点赞过了");
        }
        // 不存在，调用service 点赞
        this.spitService.updateSpitThumbupToIncrementingOld(id);
        // 点赞后保存到reids, 标记1代表已点赞
        this.redisTemplate.opsForValue().set(redisKey, "1");
        return new ResultDTO(true, StatusCode.OK, "点赞成功");
    }

}
